<template>

  <div class="quick-container">

    <div class="tabr-nav-title">
       <van-nav-bar
        title="快处上报"
        style="width: 100%; height: 44px"
        left-arrow
        @click-left="onClickLeft"
      />
    </div>
     <!-- 新增：搜索输入框
    <div class="search-box">
      <input type="text" v-model="searchKeyword" placeholder="请输入地点名称" />
      <button @click="searchLocation">搜索</button>
    </div> --> <!-- 搜索框 -->
    <div class="search-container">
       <van-search
        v-model="searchKeyword"
        placeholder="请输入搜索地点"
        @input="handleInput"
        @cancel="cancelSearch"
        @click.stop="handleSearch"
      /> <van-button type="primary" size="small" @click="handleConfirm"
        >确认</van-button
      > <van-dropdown-menu :close-on-click-outside="false"
        > <van-dropdown-item
          ref="menuRef"
          v-model="state.selectPoint"
          :options="state.pointList"
          @change="handleSelectPoint"
        /> </van-dropdown-menu
      >
    </div>
     <!-- 地图容器 -->
    <div id="map" class="map">
       <!-- 重置位置按钮 -->
      <div class="reset-position">
         <van-image :src="resetImg" @click.stop="resetPosition" />
      </div>

    </div>
     <!-- 在库点位 -->
    <div class="on-position-warp">

      <div class="title">附近在库点位</div>

      <div class="alarm-list">

        <div
          class="alarm-item"
          v-for="(item, index) in state.onPositionList"
          :key="index"
          @click="positionPoint(item)"
        >

          <div class="content">

            <div class="t1">{{ item.name }}</div>

            <div class="t2">{{ item.address }}</div>

          </div>

          <div class="confirm">

            <div class="t1">{{ item.distance }}km</div>

            <div class="t2">
               <van-button
                type="success"
                size="small"
                @click.stop="confirmPoint(item)"
                >确认</van-button
              >
            </div>

          </div>

        </div>

      </div>

    </div>

  </div>

</template>

<script setup>
  import { onMounted, reactive, ref } from 'vue'
  import L from 'leaflet'
  import 'leaflet/dist/leaflet.css'
  import resetImg from '@/assets/images/home/icon_reset_positon.png'
  import selfImg from '@/assets/images/task/loalcation.png'

  import { getUserInfo } from '../../utils/userInfo.js'
  import { getPointPlus } from '../../api/index.js'
  const userInfo = getUserInfo()
  import { getFunction } from './components/mapTools.js'

  import { useRoute, useRouter } from 'vue-router'
  const router = useRouter()

  const { calculateDistance } = getFunction()

  const pointPickerColumns = ref([])

  const state = reactive({
    // 在库点位
    onPositionList: [
      {
        id: '1806596606742552613',
        code: null,
        name: '海尔路鲁家山路口\r\n（江北区寸滩街道海尔路鲁家山路口）',
        cityCode: '500000',
        city: '重庆市',
        countyCode: '500105',
        county: '江北区',
        townCode: '500105005',
        town: '寸滩街道',
        responsibleUnit: '区交通局',
        responsibleUnitLevel: null,
        longitude: 106.627983,
        latitude: 29.622777,
        address: '海尔路鲁家山路口（江北区寸滩街道海尔路鲁家山路口）',
        status: null,
        reportor: null,
        reportContact: null,
        reportTime: null,
        remark: '',
        fileIds: '',
        sourceType: null,
        subSourceType: null,
        hourlyRainFall: null,
        waterLevelRuler: true,
        lot: false,
        camera: true,
        emergencyMeasure: null,
        manageLeader: null,
        manageLeaderPhone: null,
        rectifResponsible: null,
        rectifResponsiblePhone: null,
        controlResponsible: '王毓樊',
        controlResponsiblePhone: '17784720845',
        expert: '白静',
        expertId: null,
        expertPhone: '13883005687',
        pointType: '陡坡接缓坡路段',
        pointTypeId: '1914609063963803650',
        pointLevel: '有一定风险',
        geographicFeature: '陡坡接缓坡路段',
        topography: '地势低洼',
        stagnantWaterCauseIds: '1918953469759180802,1918953882059264001',
        actualHistoricalReproducePeriod: 10,
        designHistoricalReproducePeriod: null,
        affectRiver: null,
        standardActual: null,
        catchmentArea: null,
        warehouse: null,
        deleteFlag: 0,
        createTime: null,
        updateTime: '2025-07-04T08:36:17.062+00:00',
        version: 1,
        initStarter: true,
        focusType: '1',
        riskType: '历史风险',
        hydropsCnt: 0,
        stagnantWaterCause: '施工破坏既有排水系统/杂物堵塞雨水口',
        realLineYear: '5',
        realNlYear: '100',
        standNlYear: '100',
        centerResponsible: '朱贞臻、王炜',
        lastJstime: null,
        djCnt: 0,
        djjsHour: '118.9mm/3h（10年）',
        hydropsDeep: null,
        bz: '为缓解该处积水，江北区在该处实施顶管工程，新增管道20余米',
        jyl: null,
        drk: '0',
        jnJsd: '0',
        jnJscs: 0,
        nameOther: '江北区寸滩街道海尔路鲁家山路口',
        lastHydropstime: '2024-05-25--2024-05-26',
        recognizeStatus: null,
        refundLibraryExamine: null,
        cspsflaqResponsible: '1925230399097585665',
        csnlzlResponsible: '1925228365833224194',
        ghdwResponsible: '1934868539919810562',
        zzResponsible: null,
        zzResponsibleId: null,
        sdzdResponsible: '1934867926477684738',
        zxmbr: null,
        zxmbrId: null,
        sjResponsible: null,
        sjResponsibleId: null,
        zxmbrPhone: null,
        sjResponsiblePhone: null,
        cspsflaqResponsibleName: '楚斌',
        csnlzlResponsibleName: '刘波',
        ghdwResponsibleName: '刘波',
        sdzdResponsibleName: '文华华',
        threshold: 101.4,
        partition: '中心城区',
        pointState: '1',
        isShowHandlerBtn: null,
        count: null,
        isContingencyPlan: '1',
        btk: '0',
        bcenter: '1',
        brisk: '1',
        badd: '0',
        bzgd: '0',
        bgczz: '1',
        distance: '100',
      },
    ],
    //
    selectPoint: '',
    pointList: [
      // { text: "全部商品", value: 0 },
      // { text: "新款商品", value: 1 },
      // { text: "活动商品", value: 2 },
    ],
    selectedItem: {},
    center: [114.05, 22.55],
    queryPoint: {
      lat: '',
      lon: '',
      name: '',
      address: '',
      townCode: '',
      town: '',
    },
  })

  const TDT_CONFIG = {
    token: '3066a90efa9734ea28f5a076287495f6',
    tdtUrl: 'https://csts.zfcxjw.cq.gov.cn:38001/tiandituwmts{s}/',
    vec: 'DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=',
    cva: 'DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=',
    center: [29.555819, 106.565186],
  }
  let map
  let marker
  let selfMarker
  let moveHandler
  let moveEndHandler
  const initMap = () => {
    destroyMap()
    map = L.map('map', {
      zoomControl: false, // 如果你使用自定义控件，关闭默认缩放控件
    }).setView(TDT_CONFIG.center, 12)
    resetPosition()
    // 添加天地图瓦片图层
    L.tileLayer(TDT_CONFIG.tdtUrl + TDT_CONFIG.vec + TDT_CONFIG.token, {
      subdomains: '123456',
    }).addTo(map)
    // 添加天地图标注
    L.tileLayer(TDT_CONFIG.tdtUrl + TDT_CONFIG.cva + TDT_CONFIG.token, {
      subdomains: '123456',
    }).addTo(map)

    // 添加当前定位标签

    // 添加固定标记
    marker = L.marker(TDT_CONFIG.center, { draggable: false }).addTo(map)

    // 监听地图拖动结束事件
    moveHandler = () => {
      marker.closePopup()
      const center = map.getCenter()
      const { lat, lng } = center
      marker.setLatLng([lat, lng], { animate: true, duration: 0.3 })
    }
    map.on('move', moveHandler)

    // 【拖动结束】后获取地址并显示弹窗
    moveEndHandler = () => {
      const center = map.getCenter()
      const { lat, lng } = center
      reverseGeocode(lat, lng)
    }
    map.on('moveend', moveEndHandler)
  }

  // 逆地理编码函数
  const reverseGeocode = (lat, lng) => {
    const geocodeUrl = `https://api.tianditu.gov.cn/geocoder?postStr={"lon":${lng},"lat":${lat},"ver":1}&tk=${TDT_CONFIG.token}`

    fetch(geocodeUrl)
      .then((res) => res.json())
      .then((data) => {
        if (data.status == '0' && data.result) {
          // console.log('打印查询信息', data)
          const locationName = data.result.formatted_address

          state.queryPoint.townCode =
            data.result.addressComponent.town_code.slice(3)
          state.queryPoint.town = data.result.addressComponent.town
          state.queryPoint.lat = data.result.location.lat
          state.queryPoint.lon = data.result.location.lon
          state.queryPoint.name = data.result.addressComponent.poi
          state.queryPoint.address = data.result.formatted_address

          showMarkerWithPopup(lat, lng, locationName)
        }
      })
      .catch((err) => {
        // console.error("逆地理编码失败:", err);
        // alert("获取点位名称失败");
      })
  }

  const destroyMap = () => {
    // 1. 移除地图事件监听
    if (map) {
      map.off('move', moveHandler)
      map.off('moveend', moveEndHandler)
    }

    // 2. 移除标记及弹窗
    if (marker) {
      marker.removeFrom(map) // 从地图移除标记
      marker = null // 解除引用
    }

    // 3. 销毁地图实例
    if (map) {
      map.remove()
      map = null
    }
  }

  // 显示标记和弹窗
  const showMarkerWithPopup = (lat, lng, name) => {
    const popupContent = `
    <div style="width: 200px;">
      <div><strong>${name}</strong></div>
      <button id="popupButton" style="margin-top: 10px; padding: 5px 10px; background: #1989fa; color: white; border: none; border-radius: 4px;">确认</button>
    </div>
  `
    marker.bindPopup(popupContent).openPopup()

    // 绑定按钮点击事件
    setTimeout(() => {
      const popupButton = document.getElementById('popupButton')
      if (popupButton) {
        popupButton.addEventListener('click', handlePopupButtonClick)
      }
    }, 100)
  }

  const handlePopupButtonClick = () => {
    // 跳转表单页面
    // console.log('点击了', state.queryPoint)

    const mapChosePoint = {
      ifPint: '否',
      riskPoint: state.queryPoint.name,
      riskPointId: state.queryPoint.id,
      coordx: state.queryPoint.lon,
      coordy: state.queryPoint.lat,
      riskPointAddress: state.queryPoint.address,
      townCode: state.queryPoint.townCode,
      town: state.queryPoint.town,
    }
    localStorage.setItem('mapChosePoint', JSON.stringify(mapChosePoint))
    router.push('/quickReportSecondary')
  }

  // 重置当前位置
  const resetPosition = () => {
    // gps有定位左边走定位，没有走默认位置
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          const lat = position.coords.latitude
          const lng = position.coords.longitude
          const accuracy = position.coords.accuracy // 定位精度（米）

          console.log(`纬度: ${lat}, 经度: ${lng}, 精度: ${accuracy} 米`)

          if (map) {
            map.setView([lat, lng], 14)

            // 添加自身定位图标

            // 创建自定义图标（使用Leaflet的Icon类）
            const selfIcon = L.icon({
              iconUrl: selfImg,
              iconSize: [24, 24], // 图标大小
              // iconAnchor: [12, 41], // 图标锚点（指向位置的点）
              popupAnchor: [0, -12], // 弹窗位置偏移
            })
            // 添加自身位置标记
            selfMarker = L.marker([lat, lng], {
              icon: selfIcon, // 使用自定义图标
              draggable: false, // 自身位置通常不可拖动
              zIndexOffset: 1000, // 确保在其他标记上方显示
            }).addTo(map)

            // 添加弹窗说明
            selfMarker.bindPopup('我的位置').openPopup()

            // 筛查点位附近的点位
            state.onPositionList = []
            pointPickerColumns.value.forEach((item) => {
              const distance = calculateDistance(
                lat,
                lng,
                item.latitude,
                item.longitude,
              )
              // 5km范围
              if (distance <= 5) {
                const newItem = { ...item }
                newItem.distance = distance
                state.onPositionList.push(newItem)
              }
            })

            // 排序
            state.onPositionList.sort((a, b) => {
              return a.distance - b.distance
            })
          }
        },
        (error) => {
          console.error('获取定位失败:', error.message)
          map = L.map('map').setView(TDT_CONFIG.center, 12)

          alert('无法获取您的位置，请检查设备设置')
        },
        {
          enableHighAccuracy: true, // 启用高精度定位（如 GPS）
          timeout: 10000, // 超时时间
          maximumAge: 0, // 不使用缓存定位结果
        },
      )
    } else {
      map = L.map('map').setView(TDT_CONFIG.center, 12)
    }
  }

  // 分页参数
  const refreshing = ref(false)
  const loading = ref(false)
  const finished = ref(false)

  const listContainer = ref(null)
  const onLoad = (type) => {}

  // 搜索相关状态
  const searchKeyword = ref('')
  const searchLoading = ref(false)
  const searchFinished = ref(false)
  const currentPage = ref(1)
  const pageSize = ref(10)
  let searchTimer
  // 处理输入
  const handleInput = () => {
    if (searchTimer) {
      clearTimeout(searchTimer)
    }

    if (!searchKeyword.value.trim()) {
      return
    }

    searchTimer = setTimeout(() => {
      currentPage.value = 1
      searchFinished.value = false
      searchLocation()
    }, 500)
  }

  const menuRef = ref(null)
  // 搜索位置
  const searchLocation = () => {
    menuRef.value.toggle(true)
    if (searchLoading.value || searchFinished.value) return

    searchLoading.value = true
    const keyword = encodeURIComponent(searchKeyword.value.trim())
    const page = currentPage.value

    const postStr = {
      keyWord: keyword,
      queryType: 1,
      mapBound: '-180,-90,180,90',
      level: 18,
      start: 0,
      count: 30,
      specify: '156500000',
    }

    const searchUrl = `https://api.tianditu.gov.cn/v2/search?postStr=${JSON.stringify(
      postStr,
    )}&tk=${TDT_CONFIG.token}&page=${page}&pageSize=${pageSize.value}`

    fetch(searchUrl)
      .then((res) => res.json())
      .then((data) => {
        console.log(data, 'data')

        searchLoading.value = false
        if (data && data.pois) {
          state.pointList =
            data.pois.map((item) => {
              return {
                ...item,
                text: item.name,
                value: item.name,
              }
            }) || []
        }
      })
      .catch((err) => {
        searchLoading.value = false
        console.error('搜索失败:', err)
      })
  }

  const handleSearch = () => {
    menuRef.value.toggle()
  }
  // 选择menu项
  const handleSelectPoint = (item) => {
    // 从 pointList 中找到对应项
    state.selectedItem = state.pointList.find((point) => point.value === item)
    searchKeyword.value = state.selectedItem.name
  }

  // 点击确认
  const handleConfirm = () => {
    if (state.selectedItem.name && state.selectedItem.lonlat) {
      const [lng, lat] = state.selectedItem.lonlat.split(',')
      // 跳转地图
      if (map) {
        map.setView([lat, lng], 14)
      }

      // // 更新标记并弹窗
      // if (marker) {
      //   marker.setLatLng([lat, lng]).bindPopup(state.selectedItem.name).openPopup();
      // }
    }
  }

  // 点击在库点位定位
  const positionPoint = (item) => {
    map.off('moveend', moveEndHandler)

    // 临时事件
    const handleMoveEnd = () => {
      marker.setLatLng([item.latitude, item.longitude])
      const popupContent = `
    <div style="width: 200px;">
      <div style="text-align:center">在库点位</div>
      <div><strong>${item.name}</strong></div>
      </div>
      `
      marker.bindPopup(popupContent).openPopup()
      // 解绑临时事件
      map.off('moveend', handleMoveEnd)
      // 绑定原事件
      map.on('moveend', moveEndHandler)
    }
    // 绑定临时事件
    map.on('moveend', handleMoveEnd)

    if (map) {
      map.setView([item.latitude, item.longitude], 14)
    }
  }

  const confirmPoint = (item) => {
    // console.log('点击了', item)

    const mapChosePoint = {
      ifPint: '是',
      riskPoint: item.name,
      riskPointId: item.id,
      coordx: item.longitude,
      coordy: item.latitude,
      riskPointAddress: item.address,
      townCode: item.townCode,
      town: item.town,
    }
    localStorage.setItem('mapChosePoint', JSON.stringify(mapChosePoint))

    router.push('/quickReportSecondary')
  }

  const onClickLeft = () => {
    // destroyMap()
    history.back()
  }

  onMounted(() => {
    initMap()

    // 获取点位
    getPointPlus(userInfo.countyCode).then((res) => {
      const { data } = res.data
      // console.log('区县点位', data)
      pointPickerColumns.value = [...data]
      // pointPickerColumns.value = data?.map((item) => {
      //   return {
      //     text: item.name,
      //     value: item.name,
      //     riskPointId: item.id,
      //     address: item.address,
      //     townCode: item.townCode,
      //     lon: item.longitude, // 经度
      //     lat: item.latitude, // 纬度
      //   }
      // })
    })
  })
</script>

<style lang="less" scoped>
  .quick-container {
  height: 100%;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  .tabr-nav-title {
    display: flex;
    align-items: center;
    font-weight: 600;
    height: 44px;
    font-size: 18px;
    color: #29292c;
    text-align: center;
    font-style: normal;
    background: #fff;
    width: 100vw;
  }
  .search-container {
    // padding: 10px;
    background-color: #fff;
    position: relative;
    display: flex;
    height: 50px;
    justify-content: space-between;
    .van-button {
      margin-top: 10px;
    }
    :deep(.van-dropdown-menu__bar) {
      display: none;
    }
    :deep(.van-dropdown-item) {
      top: 90px !important;
    }

    --van-dropdown-menu-content-max-height: 40%;
  }

  .map {
    width: 100%;
    height: 100%;
    // height: calc(100vh - 120px);
    flex: 1;
    position: relative;
    overflow: hidden; // 防止内容溢出
    z-index: 1;
    .reset-position {
      position: absolute;
      right: 10px;
      bottom: 10px;
      width: 50px;
      height: 50px;
      background: #fff;
      border-radius: 5px;
      z-index: 500;
      .van-image {
        scale: 0.8;
      }
    }
  }

  .on-position-warp {
    height: 300px;
    width: 100%;
    border-radius: 5px 5px;
    // padding: 10px;
    box-sizing: border-box;
    .title {
      font-size: 14px;
      padding: 10px;
    }

    .alarm-list {
      // border: 1px red solid;
      height: calc(100% - 40px);
      overflow: auto;
      .alarm-item {
        display: flex;
        .content {
          width: 80%;
          padding: 10px;
          .t1 {
            font-size: 14px;
          }

          .t2 {
            margin-top: 5px;
            font-size: 12px;
            color: #b4b4b4;
          }
        }

        .confirm {
          .t1 {
            // padding: 10px;
            margin-top: 10px;
            margin-bottom: 5px;
            font-size: 14px;
          }
        }
        &:nth-child(odd) {
          background: #f7f7f7;
        }
      }
    }
  }
}
</style>

